import React, { useCallback, useEffect, useState, useRef } from "react";
import { message, Button, Tooltip, Modal, Image, InputNumber, Table } from "antd";
import { NumText } from "@/pages/OrderModule/common/components/CommonText";
import IconFont from "@/components/IconFont";
import CompleteCountModal from "./component/CompleteCountModal";
import QuickPurchaseModal from "./component/QuickPurchaseModal";
import FillPurchaseModal from "./component/FillPurchaseModal";
import WarehouseSelect from "@/views/components/WarehouseSelect"; // 导入WarehouseSelect组件
import PrinterConfigModal from "./component/PrinterConfigModal";
import { checkComponentsIsOpen } from "@/utils/print.jsx";
import { hiprintTipsModal } from '@/utils/utils.jsx';
import { Input, Select, BatchSuffixInput } from "@/views/components/PrefixPlaceholder";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import {
	getMakeinventoryPage,
	getCheckprintruleOp,
	cashpaymentMethod,
	cashpaymentPrint,
	makeinventoryComplete,
	getmakeinventoryConfig,
	updatePrint,
	queryAreaCode,
	batchPrintByExpressSuccessNotify,
	saveCodePrintTask,
	getKuaiMaiPrint
} from "./service";
import { usePrintExpress } from "@/views/hooks/usePrintExpress";
import { usePrintUniqueCode } from "@/views/hooks/usePrintUniqueCode";
import AreaCodeSelect from "@/pages/PurchaseModule/propose/components/Actions/AreaCodeSelect";
import CommonStoreSearchInput from "@/views/components/CommonStoreSearchInput/index";
import { CommonTable } from '@/pages/OrderModule/common/components/CommonTable';
import { excelExport } from '@/utils/utils.jsx';
import { printKmUniqcode } from '@/utils/printKm.js';

import {
	getExpressRelativePrinter,
} from "@/utils/authority";

//发货失败要导出的列
const goodColumn = [
	{
		title: '唯一码',
		dataIndex: 'uniqueCode',
		key: 'uniqueCode',
	},
	{
		title: '系统订单号',
		dataIndex: 'orderSn',
		key: 'orderSn',
	},
	{
		title: '失败原因',
		dataIndex: 'msg',
		key: 'msg',
	}
];


const MakeInventoryPage = () => {
	const [visible, setVisible] = useState(0);
	const [selectedWarehouse, setSelectedWarehouse] = useState(null);
	const [records, setReocrd] = useState(null);
	const [data, setData] = useState([]);
	const [printExpressList, setPrintExpressList] = useState([]);
	const [printCoing, setPrintConfig] = useState([]);
	const [loading, setLoading] = useState(false);
	const areaOption = useRef();

	const { printExpress, expressList } = usePrintExpress({
		callback: data => {
			if (data.successList && data.successList.length) {
				batchPrintByExpressSuccessNotify([...data.successList.map(e => e.logisticsNo)]).then(res => {
					const { success } = res;
					if (success) {
						// fetchList();
					}
				});
			}
			modalRender('打印', data?.successPrintNum, data?.failPrintNum, data?.noLogisticsNos); //打印失敗提示

		}
	}); //打印面单

	const RefPrintCard = useRef();

	const [footerDataSource, setFooterDataSource] = useState([]);
	const tableRequest = getMakeinventoryPage;
	const defaultColumns = [
		{
			name: "序号",
			code: "index",
			lock: true,
			render: (t, r, i) => {
				return i + 1;
			},
			width: 100
		},
		{
			name: "商品图片",
			code: "skuImage",
			render: (t, r, i) => {
				return <Image width={60} src={t} />;
			},
			search: {
				order: 1,
				code: "warehouse",
				content: () => {
					return <WarehouseSelect value={selectedWarehouse} placeholder={"所属仓库"} onChange={handleWarehouseChange} />;
				}
			},
			width: 200
		},
		{
			name: "供应商",
			code: "supplier",
			search: {
				order: 2,
				code: "supplierName",
				content: () => <CommonStoreSearchInput type="storeName" valueKey="storeName" placeholder="供应商名称" />
			},
			width: 200
		},
		{
			name: "区域编码",
			code: "supplierAreaName",
			width: 200,
			search: {
				code: "supplierAreaName",
				order: 3,
				content: () => (
					<AreaCodeSelect
						origin="true"
						size="middle"
						placeholder="区域编码"
						mode="multiple"
						options={areaOption.current}
						showArrow={false}
						maxTagCount={2}
						style={{ lineHeight: "22px" }}
					/>
				)
			}
		},
		{
			name: "商品名称",
			code: "skuName",
			search: {
				order: 4,
				content: () => <Input allowClear placeholder="商品名称" />
			},
			width: 200
		},
		{
			name: "商品编码",
			code: "skuCode",
			search: {
				order: 5,
				content: () => <Input allowClear placeholder="商品编码" />
			},
			width: 200
		},
		{
			name: "款式编码",
			code: "spuCode",
			search: {
				order: 6,
				content: () => <Input allowClear placeholder="款式编码" />
			},
			width: 200
		},
		{
			name: "颜色规格",
			code: "skuSpec",
			search: {
				order: 7,
				content: () => <Input allowClear placeholder="颜色规格" />
			},
			width: 200
		},
		{
			name: "采购单价",
			code: "skuPrice",
			render: value => value && <NumText style={{ color: "rgba(240, 61, 41, 1)" }} as="s1" pre="¥" num={value} />,
			width: 200
		},
		{
			name: "采购总数",
			code: "purchasedCount",
			width: 200
		},

		{
			name: "实际拿货数量",
			code: "waitCount",
			width: 200
		},
		{
			name: "本次清点数",
			code: "completeWaitCount",
			lock: true,
			render: (t, r, i) => {
				return (
					<div>
						<InputNumber
							min={0}
							max={r.purchasedCount}
							precision={0}
							key={"completeWaitCount" + r.id + t}
							value={t}
							onPressEnter={e => {
								updateTableDataByRow(r, "completeWaitCount", e.target.value, i);
							}}
							onBlur={e => {
								updateTableDataByRow(r, "completeWaitCount", e.target.value, i);
							}}
							placeholder="请输入本次清点数"
						/>
					</div>
				);
			},
			width: 200
		},
		{
			name: "采购金额",
			code: "inventoryPrice",
			render: (t, r, i) => {
				// if (r.seq == "footerDataSource")
				// 	return (
				// 		<div>
				// 			<Tooltip placement="bottom" title={tooltipTitle}>
				// 				<IconFont type="iconwenhao" />
				// 			</Tooltip>
				// 			<span>
				// 				应付清点金额
				// 				<span style={{ color: "rgba(240, 61, 41, 1)" }}>
				// 					{t ? "￥" : ""} {t ? t.toFixed(2) : ""}
				// 				</span>
				// 			</span>
				// 		</div>
				// 	);
				return (
					<div style={{ color: "rgba(240, 61, 41, 1)" }}>
						{t >= 0 ? "￥" : ""}
						{t ? t.toFixed(2) : 0}
					</div>
				);
			},
			lock: true,
			width: 200
		}
		// {
		// 	name: "操作",
		// 	code: "action",
		// 	lock: true,
		// 	render: (t, r, i) => {
		// 		// if (r.seq == "footerDataSource") return "";
		// 		return (
		// 			<div className="opera-span-common" style={{ marginRight: "10px" }} onClick={() => commonHandleClick(2, r)}>
		// 				快速采购
		// 			</div>
		// 		);
		// 	}
		// }
	];
	// const [columns, setColumns] = useState(defaultColumns);
	async function getQueryAreaCode() {
		const { success, data } = await queryAreaCode({ areaCode: "" });
		if (success) {
			areaOption.current = data.map(e => {
				return {
					...e,
					value: e.id,
					label: e.name
				};
			});
		}
	}
	const fillNumber = async status => {
		updateDataSource(pre => {
			if (status == 1) {
				pre.map(x => (x.completeWaitCount = x.purchasedCount));
				pre.map(x => (x.inventoryPrice = x.completeWaitCount * x.skuPrice));
			} else {
				pre.map(x => (x.completeWaitCount = x.waitCount));
				pre.map(x => (x.inventoryPrice = x.completeWaitCount * x.skuPrice));
			}
			const totalInventoryNum = pre.reduce((sum, item) => sum + Number(item.completeWaitCount ? item.completeWaitCount : 0), 0);
			const totalInventoryPrice = pre.reduce((sum, item) => sum + Number(item.inventoryPrice ? item.inventoryPrice : 0), 0);
			setFooterDataSource(pre => {
				return [
					{
						...pre[0],
						completeWaitCount: totalInventoryNum,
						inventoryPrice: totalInventoryPrice
					}
				];
			});
			const list = [];
			return pre.map((element, i) => {
				if (element.completeWaitCount) {
					list.push(element.id)
				}
				setTimeout(() => {
					RefTable.current.setTableSelect([...selectedKeys, ...list]);
				}, 100);
				return element;
			});
		});
	};

	//保存打印记录
	const savePrintRecord = (value) => {
		const arr = [];
		value.map(v => {
			arr.push({
				"outboundNo": v.outboundNo,
				"uniqueCode": v.code
			})
		})
		const printerConfigs = getExpressRelativePrinter();
		const __uniqueCodePrinter = printerConfigs["唯一码"];
		saveCodePrintTask({
			printerName: __uniqueCodePrinter,
			printPageType: 3,
			codePrintSaveVOList: arr
		})
	}

	const commonHandleClick = (status, r) => {
		// return printExpress(['M2406200000046','M2406170000021','M2406150000072', 'M2406150000042'])
		if (status == 1) {
			if (printCoing.oneItemConfig?.expressInvoice == 1 || printCoing.oneMoreConfig?.expressInvoice == 1) { //配置面單打印
				if (!hiprint.hiwebSocket.opened) {
					return hiprintTipsModal();
				}
				if (printExpressList.length != expressList.length) {
					Modal.info({ centered: true, content: "请前往规则设置中配置对应打印机" });
					return;
				} else {
					const totalInventoryCount = selectedRows.reduce(
						(sum, item) => sum + Number(item.completeWaitCount ? item.completeWaitCount : 0),
						0
					);
					if (totalInventoryCount) {
						makeinventoryMethodData();
					} else {
						Modal.info({ centered: true, content: "请填写至少一个本次清点数" });
					}
				}
			} else {
				const totalInventoryCount = selectedRows.reduce(
					(sum, item) => sum + Number(item.completeWaitCount ? item.completeWaitCount : 0),
					0
				);
				if (totalInventoryCount) {
					makeinventoryMethodData();
				} else {
					Modal.info({ centered: true, content: "请填写至少一个本次清点数" });
				}
			}
		} else if (status == 2) {
			if (selectedRows.length || r) {
				setVisible(status);
				if (r) {
					setReocrd(r);
				}
			} else {
				Modal.info({ centered: true, content: "请选择数据" });
			}
		} else {
			setVisible(status);
		}
	};
	const handleWarehouseChange = value => {
		setSelectedWarehouse(value);
	};

	const rowKey = "id";
	const tableKey = "MakeInventoryPage32131";
	const { RefTable, selectedKeys, fetchList, selectedRows, dataSource, query, updateDataSource, searchSimpleTableProps } = useTableConfig({
		tableKey,
		rowKey,
		columns: defaultColumns,
		tableRequest,
		pageSize: 500,
		pageSizeOptions: [50, 100, 500, 1000, 5000],
		autoFetch: true,
		expressList,
		hasPagination: true,
		hasQuickSearch: false,
		beforeQuerySearch: ({ API_DATA }) => {
			getQueryAreaCode();
			return { ...API_DATA };
		},
		resetSourceData: false,
		hasColsSetting: true,
		columnResize: true
		// footerDataSource
	});

	//是否正在打印
	const [isPrint, setIsPrint] = useState(false);

	//打印唯一码
	const printUniqueCode = async (printList) => {
		if (isPrint) {
			return message.info('打印作业正在进行中，请勿重复提交');
		}
		START_LOADING();
		const res = await getKuaiMaiPrint({
			codes: printList.map(v => v.code),
			labelType: 1
		})
		END_LOADING();
		if (res.success) {
			const printerConfigs = getExpressRelativePrinter();
			const printer = printerConfigs["唯一码"];
			if(!printer) {
				return message.info("唯一码打印请选择打印机");
			}
			setIsPrint(true);
			printKmUniqcode(JSON.parse(res.data), printer, () => {
				savePrintRecord(printList);
				setIsPrint(false);
			});
		}
	}



	const CheckStockAndNoteProps = {
		visible,
		query,
		fetchList,
		printExpressList,
		printCoing,
		data,
		selectedKeys,
		records,
		selectedRows,
		dataSource,
		handleCompleteOk(data) {
			const { successGoodsNum = 0, failGoodsNum = 0, autoShippingVOList = [], noLogisticsNos = [], failPrintNum = 0, successPrintNum = 0, justArrival = 0, cancelledVOList = [] } = data;
			if (justArrival) {
				const totalInventoryCount = selectedRows.reduce(
					(sum, item) => sum + Number(item.completeWaitCount ? item.completeWaitCount : 0),
					0
				);
				return Modal.confirm({
					icon: <IconFont type="iconjingshi" />,
					title: <span className="common-color13">提示</span>,
					content: <span>清点完成{totalInventoryCount}件商品，其中<span className="common-color9">已作废{cancelledVOList.length}件</span></span>,
					centered: true,
					okButtonProps: { disabled: !cancelledVOList.length },
					okText: '导出作废商品',
					onOk() {
						excelExport({
							fileName: '作废商品详情',
							suffix: 'csv',
							titles: goodColumn.map((item) => item.title),
							dataSource: (cancelledVOList || []).map(({ uniqueCode, orderSn, msg }) => [
								uniqueCode, orderSn, msg
							]),
						});
					}
				});
			}
			const areAllOutboundOrderNoListsEmpty = data?.arrivalMakeInventoryPrintVOList.every(item => {
				return item.outboundOrderNoList.length === 0;
			});
			(failGoodsNum + successGoodsNum != 0) && modalRender('发货', successGoodsNum, failGoodsNum, autoShippingVOList); //拿貨失敗提示

			const areCodeListEmpty = data?.arrivalMakeInventoryPrintVOList.every(item => {
				return item.codeList.length === 0;
			});
			if (!areAllOutboundOrderNoListsEmpty) {
				// const printList = data.flatMap(item => item.outboundOrderNoList);
				const list = [];
				data?.arrivalMakeInventoryPrintVOList?.map(item => {
					item?.outboundOrderNoList.map(child => {
						if (child.systemNo) {
							list.push(child.systemNo);
						}
					});
				});
				if (list?.length == 0) {
					(failPrintNum + successPrintNum != 0) && modalRender('打印', successPrintNum, failPrintNum, noLogisticsNos); //打印失敗提示
				}
				list?.length && printExpress(list, 3, { noLogisticsNos, failPrintNum, successPrintNum });
			} else {
				(failPrintNum + successPrintNum != 0) && modalRender('打印', successPrintNum, failPrintNum, noLogisticsNos); //打印失敗提示
			}
			if (!areCodeListEmpty) {
				const printList = data?.arrivalMakeInventoryPrintVOList.flatMap(item => item.codeList);
				printUniqueCode(printList);
			}
		},
		handleCancel() {
			setVisible(0);
		}
	};

	const configModalProps = {
		fetchList,
		handleOk() {
			setVisible(false);
			getMakeinventoryConfig();
		},
		handleCancel() {
			setVisible(false);
		}
	};

	//拿貨失敗和打印失敗彈出提示
	const modalRender = (text, successNum, failNum, data = []) => {
		Modal.confirm({
			width: '500px',
			title: "操作提示",
			content: <div><span className="common-color10">成功</span>{text}{successNum}个商品，<span className="common-color9">失败</span>{text}{failNum}个商品
				{
					data.length ? <CommonTable bordered style={{ marginTop: 16 }} dataSource={data} columns={goodColumn} pagination={false} scroll={{ y: '40vh' }} /> : ''
				}
			</div>,
			okText: "导出失败内容",
			okButtonProps: { size: "large", block: true, disabled: data.length == 0 ? true : false }, //失败条数为0时不能导出失败内容
			onOk() {
				excelExport({
					fileName: '失败详情',
					suffix: 'csv',
					titles: goodColumn.map((item) => item.title),
					dataSource: (data || []).map(({ uniqueCode, orderSn, msg }) => [
						uniqueCode, orderSn, msg
					]),
				})
			},
		});
	}

	const updateTableDataByRow = (row, key, value, index) => {
		// const reg = /^[1-9]\d*$/;

		// if (reg.test(value)) {
		row[key] = value ? Number(value) : 0;
		row.inventoryPrice = row.completeWaitCount * row.skuPrice;
		updateDataSource(pre => {
			pre.forEach(i => {
				if (i.completeWaitCount > i.purchasedCount) {
					i.completeWaitCount = i.purchasedCount;
				}
			});
			pre.map(x => (x.completeWaitCount = x.completeWaitCount ? x.completeWaitCount : 0));
			pre.map(x => (x.inventoryPrice = x.completeWaitCount * x.skuPrice));
			const totalInventoryNum = pre.reduce((sum, item) => sum + Number(item.completeWaitCount ? item.completeWaitCount : 0), 0);
			const totalInventoryPrice = pre.reduce((sum, item) => sum + Number(item.inventoryPrice ? item.inventoryPrice : 0), 0);
			setFooterDataSource(pre => {
				return [
					{
						...pre[0],
						completeWaitCount: totalInventoryNum,
						inventoryPrice: totalInventoryPrice
					}
				];
			});
			const list = [];
			// if(row.waitCount )
			return pre.map((element, i) => {
				// const 
				setTimeout(() => {
					RefTable.current.setTableSelect([...selectedKeys, row.id]);
				}, 100);
				return element;
			});
		});
		// } else {
		// 	message.info("请输入正整数");
		// }
	};
	const makeinventoryCompleteFn = async () => {
		let val = {
			takeGoodList: selectedRows,
			print: printExpressList
		};
		const { data = {}, success } = await makeinventoryComplete(val);

		if (success) {
			fetchList();
			const { failGoodsNum = 0, successGoodsNum = 0, autoShippingVOList = [], noLogisticsNos = [], failPrintNum = 0, successPrintNum = 0, justArrival = 0, cancelledVOList = [] } = data;
			if (justArrival) {
				const totalInventoryCount = selectedRows.reduce(
					(sum, item) => sum + Number(item.completeWaitCount ? item.completeWaitCount : 0),
					0
				);
				return Modal.confirm({
					icon: <IconFont type="iconjingshi" />,
					title: <span className="common-color13">提示</span>,
					content: <span>清点完成{totalInventoryCount}件商品，其中<span className="common-color9">已作废{cancelledVOList.length}件</span></span>,
					centered: true,
					okButtonProps: { disabled: !cancelledVOList.length },
					okText: '导出作废商品',
					onOk() {
						excelExport({
							fileName: '作废商品详情',
							suffix: 'csv',
							titles: goodColumn.map((item) => item.title),
							dataSource: (cancelledVOList || []).map(({ uniqueCode, orderSn, msg }) => [
								uniqueCode, orderSn, msg
							]),
						});
					}
				});
			}
			const areAllOutboundOrderNoListsEmpty = data.arrivalMakeInventoryPrintVOList.every(item => {
				return item.outboundOrderNoList.length === 0;
			});
			const areCodeListEmpty = data.arrivalMakeInventoryPrintVOList.every(item => {
				return item.codeList.length === 0;
			});

			// if (areCodeListEmpty && areAllOutboundOrderNoListsEmpty) {
			// 	fetchList();
			// }
			(failGoodsNum + successGoodsNum != 0) && modalRender('发货', successGoodsNum, failGoodsNum, autoShippingVOList); //拿貨失敗提示

			if (!areAllOutboundOrderNoListsEmpty) {
				// const printList = data.flatMap(item => item.outboundOrderNoList).flatMap(item);
				const list = [];
				data?.arrivalMakeInventoryPrintVOList?.map(item => {
					item?.outboundOrderNoList.map(child => {
						if (child.systemNo) {
							list.push(child.systemNo);
						}
					});
				});
				if (list?.length == 0) {
					(failPrintNum + successPrintNum != 0) && modalRender('打印', successPrintNum, failPrintNum, noLogisticsNos); //打印失敗提示
				}
				list?.length && printExpress(list, 3, { noLogisticsNos, failPrintNum, successPrintNum });
				// printExpress(printList);
			} else {
				(failPrintNum + successPrintNum != 0) && modalRender('打印', successPrintNum, failPrintNum, noLogisticsNos); //打印失敗提示
			}
			if (!areCodeListEmpty) {
				const printList = data?.arrivalMakeInventoryPrintVOList.flatMap(item => item.codeList);
				printUniqueCode(printList);
				// 	const d = printList.map(e => {
				// 		return {
				// 			uniqueCode: e.code, //"条形码",
				// 			codeSN: e.nums, // "序号",
				// 			orderGoodsCount: e.skuQuantity, //"订单商品数量",
				// 			orderGoodsName: e.skuName, // "订单商品名称",
				// 			orderGoodsSpec: e.skuSpec, //"订单规格属性",
				// 			salesOrderSn: e.outboundNo, // "销售出库单号"
				// 			sysSkuId: e.skuCode, //"商品编码",
				// 			basketName: e.sortingBoxName, //"分拣框",
				// 			waveName: e.skuQuantity > 1 ? "多" : "单" //"订单类型",
				// 		};
				// 	});
				//           const printerConfigs = getExpressRelativePrinter();
				//           const __uniqueCodePrinter = printerConfigs["唯一码"];
				//           if(__uniqueCodePrinter) {
				//               initPrint(d);
				//               savePrintRecord(printList);
				//           } else {
				//               message.info("唯一码打印请选择打印机")
				//           }
			}
		}
	};

	//获取完成清点打印规则
	const getMakeinventoryConfig = async () => {
		const { data, success } = await getmakeinventoryConfig();
		if (success) {
			if (data) {
				setPrintConfig(data);
			}
		}
	};
	// useEffect(() => {
	// 	setSelectList(selectedRows);
	// }, [selectedRows]);
	const makeinventoryMethodData = async () => {
		const printerConfigs = getExpressRelativePrinter();

		let param = {
			takeGoodList: selectedRows,
			isDeduction: 0,
			payType: 0
		};
		const { data, success } = await cashpaymentMethod(param);
		if (success) {
			setData(data);
			if (data.meetTotalAmount == 0) {
				Modal.info({
					title: "完成清点",
					content: (
						<div style={{ marginTop: 24, marginLeft: 45 }}>
							本次清点数:<span style={{ color: "rgba(0, 188, 117, 1)", marginLeft: 5 }}>{data.count}</span>
						</div>
					),
					centered: true,
					onOk() {
						makeinventoryCompleteFn();
					}
				});
			} else {
				setVisible(1);
			}
		}
	};
	useEffect(() => {
		// 保存的是express的name作为key
		const obj = getExpressRelativePrinter() || {};
		let keys = Object.keys(obj);
		let print = [];
		for (var key in obj) {
			// 检查键是否是对象自身的属性，而不是原型链上的
			if (obj.hasOwnProperty(key)) {
				// 输出键和对应的值
				expressList.forEach(i => {
					if (i.name == key) {
						print.push({ expressCompany: i.name, printName: obj[key] });
					}
				});
			}
		}
		setPrintExpressList(print);
	}, [dataSource]);
	const combineList = (arr1, arr2) => arr1.concat(arr2);
	const handleChildValueChange = value => {
		value.forEach(i => {
			dataSource.forEach(j => {
				if (j.skuCode == i.skuCode) {
					let data = { code: i.code };
					if (combineList(j.makeInventoryList, j.waitCountList).includes(i.code)) {
						j.uniqueCodeList.push(data);
					}
					j.uniqueCodeList = j.uniqueCodeList.filter((item, index) => {
						return j.uniqueCodeList.findIndex(other => other.code === item.code) === index;
					});
					updateDataSource(pre => {
						pre.map(x => {
							if (combineList(x.makeInventoryList, x.waitCountList).includes(i.code)) {
								return x.completeWaitCount = x.uniqueCodeList.length ? x.uniqueCodeList.length : 0;
							}
						});
						pre.map(x => {
							if (combineList(x.makeInventoryList, x.waitCountList).includes(i.code)) {
								return x.inventoryPrice = x.completeWaitCount * x.skuPrice;
							}
						})
						const totalInventoryNum = pre.reduce(
							(sum, item) => sum + Number(item.completeWaitCount ? item.completeWaitCount : 0),
							0
						);
						const totalInventoryPrice = pre.reduce((sum, item) => sum + Number(item.inventoryPrice ? item.inventoryPrice : 0), 0);
						setFooterDataSource(pre => {
							return [
								{
									...pre[0],
									completeWaitCount: totalInventoryNum,
									inventoryPrice: totalInventoryPrice
								}
							];
						});
						const list = [];
						return pre.map((element, i) => {
							if (element.completeWaitCount) {
								list.push(element.id)
							}
							setTimeout(() => {
								RefTable.current.setTableSelect([...selectedKeys, ...list]);
							}, 100);
							return element;
						});
					});
				}
			});
		});
	};

	useEffect(() => {
		setLoading(true);
		checkComponentsIsOpen(
			undefined,
			res => {
				setLoading(false);
				if (res.errArr) {
					const content = (
						<div>
							检测到您未开启<span style={{ fontWeight: "bold", wordBreak: "break-all" }}>【{res.errArr.join("，")}】</span>
							打印组件，为不影响相关订单打印功能，请先及时开启（打印组件可去ERP首页进行下载）
						</div>
					);
					Modal.info({ centered: true, content });
				}
			},
			false
		);
		// getCheckprintruleFunc();
		getMakeinventoryConfig();
	}, []);
	const LeftBtns = (
		<>
			<Button style={{ color: "#fff" }} type="primary" onClick={() => commonHandleClick(1)}>
				完成清点
			</Button>
			{/* <Button onClick={() => commonHandleClick(2)}>快速采购</Button> */}
			<Button onClick={() => fillNumber(1)}>采购数填充清点数</Button>
			<Button onClick={() => fillNumber(2)}>拿货数填充清点数</Button>
			<Button onClick={() => commonHandleClick(3)}>扫码填充</Button>
		</>
	);
	const RightBtns = (
		<>
			<span className="common-color2">
				<IconFont type="iconsetting" />
				&nbsp;
				<span onClick={() => setVisible(4)}>规则设置</span>
			</span>
		</>
	);

	return (
		<>
			<SearchCheckboxTable key={tableKey} leftBtns={LeftBtns} rightBtns={RightBtns} mounted={false} {...searchSimpleTableProps} />
			{visible == 1 && <CompleteCountModal {...CheckStockAndNoteProps} />}
			{visible == 2 && <QuickPurchaseModal {...CheckStockAndNoteProps} />}
			{visible == 3 && <FillPurchaseModal onChildValueChange={handleChildValueChange} {...CheckStockAndNoteProps} />}
			{visible == 4 && <PrinterConfigModal ref={RefPrintCard} {...configModalProps} />}
		</>
	);
};

export default React.memo(MakeInventoryPage, () => {
	return true;
});
